package net.expectx.common.single.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV工具类
 * @author lijian
 */
public class CsvUtils {
    private static String fileName;

    public static void load(String file) {
        fileName = file;
    }

    private static boolean checkAndCreateFile() {

        File file = new File(fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean readCSV() throws IOException {
        ArrayList<String[]> list = new ArrayList<String[]>();
        try {
            CsvReader reader = new CsvReader(fileName, ',', Charset.forName("gb2312"));
            reader.readHeaders();
            while (reader.readRecord()) {
                list.add(reader.getValues());
            }
            reader.close();
            for (int row = 0; row < list.size(); row++) {
                int length = list.get(row).length;
                if (length > 0) {
                    for (int i = 0; i < length; i++) {
                        System.out.print(list.get(row)[i] + ",");
                    }//for

                }//if
                System.out.println("");
            }//for
            return true;
        } catch (Exception e) {
            return false;
        }

    }//class

    public static boolean writeCSV(String[] headers, List<String[]> datas) throws IOException {
        try {
            checkAndCreateFile();
            CsvWriter wr = new CsvWriter(fileName, ',', Charset.forName("gb2312"));
            wr.writeRecord(headers);
            for (int i = 0; i < datas.size(); i++) {
                String[] data = datas.get(i);
                wr.writeRecord(data);
            }
            wr.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String [] args) throws IOException {
        load("F:\\Workspace\\ijianhun.com\\ttfootball-collect\\src\\main\\webapp\\upload\\csv\\ssgCatapult\\ssgCatapult.csv");
        readCSV();
    }
}
